package com.eden.util;

import com.eden.entity.BasisInfo;
import com.eden.entity.ResultJson;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * ClassName: FreemarkerUtil
 * Package: com.eden.util
 * Description: FreeMarker工具类
 * Date:  2020/10/19 9:07
 *
 * @Author: 李秉林
 */
public class FreemarkerUtil {
	
	/**
	 * @param dataModel    数据引擎
	 * @param templateName 模板名称
	 * @param filePath     文件路径
	 *
	 * @return ResultJson
	 */
	public static ResultJson createFile(BasisInfo dataModel, String templateName, String filePath) {
		ResultJson result = new ResultJson();
		FileWriter out = null;
		String fileName = dataModel.getEntityName() + PathUtil.generatorFileName(templateName);
		try {
			// 通过FreeMarker的Configuration读取相应的模板文件
			Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
			// 设置模板路径
			configuration.setClassForTemplateLoading(FreemarkerUtil.class, "/freemarker/ftl/");
			// 设置默认字体
			configuration.setDefaultEncoding("utf-8");
			// 获取模板
			Template template = configuration.getTemplate(templateName);
			File file = new File(filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			} else {
				result.setCode(-1);
				result.setMessage("已经存在" + fileName);
				return result;
			}
			
			//设置输出流
			out = new FileWriter(file);
			//模板输出静态文件
			template.process(dataModel, out);
			result.setCode(200);
			result.setMessage("创建" + fileName + "成功");
			result.setSuccess(true);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		result.setCode(404);
		result.setMessage("创建" + fileName + "失败");
		result.setSuccess(false);
		return result;
	}
}
